<?php

/**
 * AJAX CRUD Controller Class
 * The following variables are available in this template:
 * - $this: the CrudCode object
 *
 * @author LongLT
 */
class MenuController extends ControllerBase {

    public function init() {
        Util::app()->theme = ADMIN_THEME;
        parent::init();
        $this->registerFancybox();
    }

    public function registerFancybox() {
        // Add jQuery library
        // Util::clientScript()->registerCoreScript('jquery');
        // Add mousewheel plugin (this is optional)
        Util::registerScriptFile(Util::themeUrl() . '/js/fancybox/jquery.mousewheel-3.0.6.pack.js', CClientScript::POS_HEAD);

        // Add fancyBox main JS and CSS files
        Util::registerScriptFile(Util::themeUrl() . '/js/fancybox/jquery.fancybox.js?v=2.0.6');
        Util::registerCssFile(Util::themeUrl() . '/js/fancybox/jquery.fancybox.css?v=2.0.6', 'screen');

        // Add Button helper (this is optional)
        // Util::registerScriptFile(Util::themeUrl() . '/js/fancybox/helpers/jquery.fancybox-buttons.css?v=1.0.2');
        // Util::registerCssFile(Util::themeUrl().'/js/fancybox/helpers/jquery.fancybox-buttons.js?v=1.0.2','screen');
        // Add Thumbnail helper (this is optional)
        // Util::registerScriptFile(Util::themeUrl() . '/js/fancybox/helpers/jquery.fancybox-thumbs.css?v=1.0.2');
        // Util::registerCssFile(Util::themeUrl().'/js/fancybox/helpers/jquery.fancybox-thumbs.js?v=1.0.2','screen');
        // Add Media helper (this is optional)
        // Util::registerScriptFile(Util::themeUrl() . '/js/fancybox/helpers/jquery.fancybox-media.js?v=1.0.0');

        if (isset($_GET['ajax']))
            $this->layout = '//layouts/none';
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array('model' => $this->loadModel($id)));
    }

    /**
     * Creates a new model.
     */
    public function actionCreate() {
        $model = new Menu;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        $parent = (Util::user()->id == 1) ? array() : Menu::buildDataForList(Menu::buildTree(1));
        if (isset($_POST['Menu'])) {
            $model->attributes = $_POST['Menu'];
            if ($model->save()) {
                $this->setFlash('Menu has been created.');
                $this->refresh();
            }
        }

        $this->render('create', array(
            'model' => $model,
            'parent' => $parent
        ));
    }

    /**
     * Updates a particular model.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        $parent = Menu::buildDataForList(Menu::buildTree($model->type_id), $model->id);

        if (isset($_POST['Menu'])) {
            $model->attributes = $_POST['Menu'];
            if ($model->save()) {
                $this->setFlash('Menu has been updated.');
                $this->refresh();
            }
        }

        $this->render('update', array(
            'model' => $model,
            'parent' => $parent
        ));
    }

    /**
     * Deletes a particular model.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete() {
        if (Yii::app()->request->isPostRequest) {
            $ids = $_POST['chk'];
            if (is_array($ids))
                foreach ($ids as $key)
                    $rs = Menu::model()->deleteByPk($key);
            if (isset($_GET['ajax'])) {
                echo CHtml::tag('div', array('class' => 'flash-success'), "Term ID #{$key} has been deleted.");
                exit;
            } else {
                $this->setFlash("Menu ID #{$key} has been deleted.");
                $this->redirect(array('index'));
            }
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Manages all models.
     */
    public function actionIndex() {
        $model = new Menu('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Menu']))
            $model->attributes = $_GET['Menu'];

        $this->render('index', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Menu::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'menu-form') {
            echo CActiveForm::validate($model);
            Util::app()->end();
        }
    }

    public function actionLoadDynamicType() {
        $vid = (int) isset($_REQUEST['Menu']['type_id']) ? $_REQUEST['Menu']['type_id'] : $_REQUEST['type_id'];
        $eliminateId = isset($_REQUEST['update_id']) ? $_REQUEST['update_id'] : '';

        $term = Menu::buildDataForList(Menu::buildTree($vid), $eliminateId);
        foreach ($term as $key => $value)
            echo CHtml::tag('option', array('value' => $key), CHtml::encode($value), true);

        exit;
    }

    public function actionGenerateAlias() {
        echo StringUtil::toAlias($_POST['Menu']['name']);
        exit;
    }

    public function actionUpdate_status($id) {
        $model = $this->loadModel($id);
        $model->status = ($model->status == 1) ? 0 : 1;
        $model->update('status');
        exit;
    }

}
